package com.corx.network.core.manager;

import com.corx.network.core.handler.NetworkStateHandler;
import com.corx.network.core.type.NetworkStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author gx
 * @version 1.0.0
 */
@Slf4j
public class NetworkStateManager implements DisposableBean {

    private final List<NetworkStateHandler> listeners = new CopyOnWriteArrayList<>();


    public void notifyStateChange(String networkId, NetworkStateEnum newState) {
        for (NetworkStateHandler listener : listeners) {
            try {
                listener.onChange(networkId, newState);
            } catch (Exception e) {
                log.error("通知连接状态变化异常", e);
            }
        }
    }

    public void register(NetworkStateHandler handler) {
        listeners.add(handler);
    }

    public void remove(NetworkStateHandler handler) {
        listeners.remove(handler);
    }

    @Override
    public void destroy() {
        log.info("NetworkStateManager销毁中...");
        listeners.clear();
    }
}

